package com.zf.yichat.api.controller.fanli;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zf.yichat.api.controller.BaseController;
import com.zf.yichat.api.dto.request.FanliApplyRequest;
import com.zf.yichat.api.dto.request.FanliListRequest;
import com.zf.yichat.dto.FanliGiveAndGoodsDetailDto;
import com.zf.yichat.mapper.FanliGoodsGiveMapper;
import com.zf.yichat.mapper.FanliGoodsReceiveMapper;
import com.zf.yichat.model.FanliGoodsGive;
import com.zf.yichat.model.FanliGoodsReceive;
import com.zf.yichat.service.FanliService;
import com.zf.yichat.service.UserService;
import com.zf.yichat.utils.YiChatMsgCode;
import com.zf.yichat.utils.common.DateUtils;
import com.zf.yichat.utils.common.DtoChangeUtils;
import com.zf.yichat.utils.common.SysInternPool;
import com.zf.yichat.utils.common.ValidUtils;
import com.zf.yichat.utils.response.FsPage;
import com.zf.yichat.utils.response.FsResponse;
import com.zf.yichat.utils.response.FsResponseGen;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.Contracts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author idea
 * @date Created in 2020/11/9 14:05
 * @description
 */
@RestController
@RequestMapping("fanli")
public class FanliController extends BaseController {
    @Autowired
    FanliService fanliService;
    @Autowired
    UserService userService;
    @Resource
    FanliGoodsReceiveMapper fanliGoodsReceiveMapper;
    @Resource
    FanliGoodsGiveMapper fanliGoodsGiveMapper;

    @PostMapping("list")
    public FsResponse list(@RequestBody FanliListRequest request) {
        FsPage fsPage = FsPage.init(request.getPageNo(), request.getPageSize());
        String query = request.getQuery();
        return getTbFanliResponse(fsPage, query);
    }

    @PostMapping("tbk/list")
    public FsResponse dgMaterialOptional(@RequestBody FanliListRequest request) {
        FsPage fsPage = FsPage.init(request.getPageNo(), request.getPageSize());
        String query = request.getQuery();
        return getTbFanliResponse(fsPage, query);
    }

    @PostMapping("dh/list")
    public FsResponse getTrillItemList(@RequestBody FanliListRequest request) {
        FsPage fsPage = FsPage.init(request.getPageNo(), request.getPageSize());
        String query = request.getQuery();
        return fanliService.getTrillItemList(fsPage, query);
    }

    @PostMapping("jdlm/list")
    public FsResponse jd(@RequestBody FanliListRequest request) {
        FsPage fsPage = FsPage.init(request.getPageNo(), request.getPageSize());
        String query = request.getQuery();
        return getJdFanliResponse(fsPage, query);
    }

    @PostMapping("daily/create")
    public FsResponse createDaily(@RequestBody FanliListRequest request) {
        Contracts.assertNotNull(request.getQuery(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        Contracts.assertNotNull(request.getDate(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        try {
            JSONObject.parseObject(request.getQuery());
        } catch (Exception e) {
            return FsResponseGen.failMsg("参数值错误");
        }
        Date date = DateUtils.parse(request.getDate());
        if (Objects.isNull(date)) {
            return FsResponseGen.failMsg("date格式错误");
        }
        return fanliService.createDaily(request.getQuery(), date);
    }

    @PostMapping("daily")
    public FsResponse getDaily() {
        return fanliService.getDaily();
    }

    private FsResponse getJdFanliResponse(FsPage fsPage, String query) {
        if (StringUtils.isNotEmpty(query)) {
            String tbk = ValidUtils.isTkl(query);
            if (Objects.nonNull(tbk)) {
                //淘口令
                return fanliService.doItemHighCommissionPromotionLinkByTpwd(query);
            } else if (ValidUtils.isUrl(query) && query.contains("jd.com")) {
                //京东口令
                if (query.indexOf(".html") > 0) {
                    query = query.substring(0, query.indexOf(".html"));
                    query = query.substring(query.lastIndexOf("/") + 1);
                }
                return fanliService.getJdUnionItems(fsPage, query, true);
            } else {
                return fanliService.getJdUnionItems(fsPage, query, false);
            }
        } else {
            return fanliService.getJfItems(fsPage);
        }
    }

    private FsResponse getTbFanliResponse(FsPage fsPage, String query) {
        if (StringUtils.isNotEmpty(query)) {
            String tbk = ValidUtils.isTkl(query);
            if (Objects.nonNull(tbk)) {
                //淘口令
                return fanliService.doItemHighCommissionPromotionLinkByTpwd(query);
            } else if (ValidUtils.isUrl(query) && query.contains("jd.com")) {
                //京东口令
                if (query.indexOf(".html") > 0) {
                    query = query.substring(0, query.indexOf(".html"));
                    query = query.substring(query.lastIndexOf("/") + 1);
                }
                return fanliService.getJdUnionItems(fsPage, query, true);
            } else {
                return fanliService.dgMaterialOptional(fsPage, query);
            }
        } else {
            return fanliService.dgOptimusMaterial(fsPage);
        }
    }

    //    @PostMapping("tbk/beian")
    //    public FsResponse setTbkQdBeiAn() {
    //        return fanliService.setTbkQdBeiAn(getUserId());
    //    }

    @PostMapping("tbk/translink")
    public FsResponse transLink(@RequestBody FanliListRequest request) {
        Contracts.assertNotNull(request.getQuery(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

        //        return fanliService.doItemHighCommissionPromotionLinkByTpwd(tbk);
        //        //        return fanliService.doItemHighCommissionPromotionLink(getUserId(), Long.valueOf(request.getQuery()));
        return null;
    }

    @PostMapping("jdlm/translink")
    public FsResponse jdTransLink(@RequestBody FanliListRequest request) {
        Contracts.assertNotNull(request.getQuery(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
        return fanliService.doItemCpsUrl(request.getQuery());
    }

    /**
     * 领取返利
     *
     * @param request
     * @return
     */
    @PostMapping("receive")
    public FsResponse receive(@RequestBody FanliGoodsReceive request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            Contracts.assertNotNull(request.getZkFinalPrice(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getUserType(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            //米选的领取在packetController
            if (request.getUserType() == 3) {
                return FsResponseGen.failMsg("userType错误");
            }

            request.setUserId(getUserId());
            request.setStatus(0);
            request.setCtime(new Date());
            request.setRealMoney(fanliService.countFanliMoney(request.getZkFinalPrice(), request.getCouponAmount() == null ? null : new BigDecimal(request.getCouponAmount()), request.getCommissionRate()));
            fanliGoodsReceiveMapper.insertSelective(request);
            return FsResponseGen.success();
        }
    }

    /**
     * 领取返利列表
     *
     * @return
     */
    @PostMapping("receive/list")
    public FsResponse receiveList(@RequestBody FanliListRequest request) {
        FsPage page = FsPage.init(request.getPageNo(), request.getPageSize());
        PageHelper.startPage(page.getPageNo(), page.getPageSize());

        Example example = new Example(FanliGoodsReceive.class);
        example.createCriteria().andEqualTo("userId", getUserId());
        example.setOrderByClause(" utime desc");
        List<FanliGoodsReceive> list = fanliGoodsReceiveMapper.selectByExample(example);
        return DtoChangeUtils.getPageList(list, v -> fanliService.getFanliGoodsReceiveDto(v));
    }

    /**
     * 领取返利列表
     *
     * @return
     */
    @PostMapping("receive/info")
    public FsResponse receiveMoney() {
        return FsResponseGen.successData(fanliGoodsReceiveMapper.selectReceiveCount(getUserId()));
    }

    /**
     * 申请返利
     *
     * @param request
     * @return
     */
    @PostMapping("apply")
    public FsResponse apply(@RequestBody FanliApplyRequest request) {
        synchronized (SysInternPool.INSTANCE.internUid(getUserId())) {
            Contracts.assertTrue(userService.validStatus(getUserId()), "未实名认证");

            Contracts.assertNotEmpty(request.getImgs(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
            Contracts.assertNotNull(request.getFanliGoodsId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());

            FanliGoodsReceive goodsReceive = fanliGoodsReceiveMapper.selectByPrimaryKey(request.getFanliGoodsId());
            Contracts.assertTrue(Objects.nonNull(goodsReceive) && Objects.equals(getUserId(), goodsReceive.getUserId()) && (goodsReceive.getStatus() == 0 || goodsReceive.getStatus() == 3), YiChatMsgCode.FANLI_NONE.msg());
            FanliGoodsGive give = new FanliGoodsGive();
            give.setGoodsId(request.getFanliGoodsId());
            give.setImgs(request.getImgs());
            give.setMemo(request.getMemo());
            give.setUserId(goodsReceive.getUserId());
            give.setStatus(0);
            give.setCtime(new Date());
            fanliGoodsGiveMapper.insertSelective(give);

            //更新返利状态为待审核
            goodsReceive.setStatus(1);
            fanliGoodsReceiveMapper.updateByPrimaryKey(goodsReceive);
            return FsResponseGen.success();
        }
    }

    /**
     * 返利申请/审核列表
     *
     * @param request
     * @return
     */
    @PostMapping("apply/list")
    public FsResponse applyList(@RequestBody FanliApplyRequest request) {
        FsPage page = FsPage.init(request.getPageNo(), request.getPageSize());
        PageHelper.startPage(page.getPageNo(), page.getPageNo());
        List<FanliGiveAndGoodsDetailDto> list = fanliGoodsGiveMapper.selectFanliApplyList(getUserId(), request.getFanliGoodsId() == null ? null : request.getFanliGoodsId());
        return DtoChangeUtils.getPageList(list, v -> fanliService.getFanliGiveAndReceiveDetailDto(v));
    }

    //    /**
    //     * 返利申请/审核详情
    //     *
    //     * @param request
    //     * @return
    //     */
    //    @PostMapping("apply/detail")
    //    public FsResponse applyDetail(@RequestBody FanliCheckRequest request) {
    //        Contracts.assertNotNull(request.getApplyId(), YiChatMsgCode.SYSTEM_PARAM_ERROR.msg());
    //        FanliGoodsGive give = fanliGoodsGiveMapper.selectByPrimaryKey(request.getApplyId());
    //        Contracts.assertTrue(give.getUserId() == getUserId(), YiChatMsgCode.GROUP_SET.msg());
    //        return FsResponseGen.successData(give);
    //    }
}
